<script lang="ts">
    import { getContext } from "svelte";
    import { AccordionContextKey } from "./Accordion.svelte";
    import { slide } from "svelte/transition";
    import { useClassList } from "../utils/useClassList";
    import type { AccordionItemProps } from "./Accordion";
    import Icon from "../Common/Icons/Icon.svelte";

    const ctx: any = getContext(AccordionContextKey);
    const props: AccordionItemProps = $props();
    const multi = ctx?.flex ? false : ctx?.multi;
    let opened = $state(false);

    const classList = $derived(
        useClassList(props, "cm-accordion-item", {
            "cm-accordion-item-active": opened,
            "cm-accordion-item-full": opened,
        })
    );

    const onTitleClick = () => {
        let v;
        let open = false;
        let activeKey = ctx.getActiveKey();
        if (!multi) {
            if (activeKey === props.name) {
                if (ctx?.flex) {
                    return;
                }
                v = "";
                open = false;
            } else {
                v = props.name;
                open = true;
            }
        } else {
            const currentKey = activeKey;
            if (currentKey.includes(props.name)) {
                const index = currentKey.indexOf(props.name);
                currentKey.splice(index, 1);
                v = [].concat(currentKey);
                open = false;
            } else {
                currentKey.push(props.name);
                v = [].concat(currentKey);
                open = true;
            }
        }
        ctx?.onSelect?.({
            name: props.name,
            open,
            openKeys: v,
        });
    };

    $effect(() => {
        let open = false;
        const currentKey = ctx.getActiveKey();

        if (!multi) {
            open = currentKey === props.name;
        } else {
            open = currentKey.includes(props.name);
        }
        opened = open;
    });
</script>

<div class={classList}>
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <div class="cm-accordion-title" onclick={onTitleClick}>
        {@render props.icon?.()}
        <div class="cm-accordion-item-title-text">
            {#if typeof props.title === "function"}
                {@render props.title()}
            {:else}
                {props.title}
            {/if}
        </div>
        <Icon icon="chevronRight" class="cm-accordion-title-arrow" size={14} />
    </div>
    {#if opened}
        <div class="cm-accordion-content" in:slide out:slide>{@render props.children?.()}</div>
    {/if}
</div>
